import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('@/views/Login')
  },
  {
    path: '/layout',
    component: () => import('@/views/Layout'),
    redirect: '/layout/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/Home'),
        meta: { isRecord: true, top: 0 } // isRecord是否需要设置滚动位置
      },
      {
        path: 'user',
        component: () => import('@/views/User')
      }
    ]
  },
  {
    path: '/search',
    component: () => import('@/views/Search')
  },
  {
    path: '/search/:keywords',
    component: () => import('@/views/Search/SearchResult.vue')
  },
  {
    path: '/article_detail',
    component: () => import('@/views/ArticleDetail')
  },
  {
    path: '/user_editor',
    component: () => import('@/views/User/UserEdit.vue')
  },
  {
    path: '/chat',
    component: () => import('@/views/Chat')
  }
]

const router = new VueRouter({
  routes
})

// 全局前置路由守卫
// router.beforeEach((to, from, next) => {
//   // 有token, 不能去登录页
//   // 无token, 需要用户"权限"的才需要去登录页
//   if (store.state.token.length > 0 && to.path === '/login') {
//     // 证明有token-已经登录了
//     next(false) // 阻止跳转原地呆着
//   } else {
//     next()
//   }
// })

// 全局后置钩子
router.afterEach((to, from) => {
  // 如果当前的路由的元信息中，isRecord 的值为 true
  if (to.meta.isRecord) {
    setTimeout(() => {
      // 则把元信息中的 top 值设为滚动条纵向滚动的位置
      window.scrollTo(0, to.meta.top)
    }, 0)
  }
})

export default router
